package com.dms.modules.community.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.community.dto.CommunityPostDetailDTO;
import com.dms.modules.community.dto.CommunitySearchDTO;
import com.dms.modules.community.service.CommunitySearchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import java.util.List;

@Slf4j
@Api(tags = "社区搜索接口")
@RestController
@RequestMapping("/community/search")
public class CommunitySearchController {

    @Autowired
    private CommunitySearchService searchService;

    @PostMapping("/record")
    @ApiOperation("记录搜索历史")
    public ApiResponse<Void> recordSearch(
            @RequestAttribute("userId") Long userId,
            @RequestParam String keyword,
            @RequestParam(required = false) Long categoryId) {
        searchService.recordSearch(userId, keyword, categoryId);
        return ApiResponse.success();
    }

    @GetMapping("/recent")
    @ApiOperation("获取用户最近搜索历史")
    public ApiResponse<List<CommunitySearchDTO>> getRecentSearches(
            @RequestAttribute("userId") Long userId,
            @ApiParam(value = "返回记录数限制", defaultValue = "10")
            @RequestParam(defaultValue = "10") Integer limit) {
        return ApiResponse.success(searchService.getUserRecentSearches(userId, limit));
    }

    @GetMapping("/hot")
    @ApiOperation("获取热门搜索词")
    public ApiResponse<List<CommunitySearchDTO>> getHotKeywords(
            @ApiParam(value = "返回记录数限制", defaultValue = "10")
            @RequestParam(defaultValue = "10") Integer limit) {
        return ApiResponse.success(searchService.getHotKeywords(limit));
    }

    @DeleteMapping("/clear")
    @ApiOperation("清空用户搜索历史")
    public ApiResponse<Boolean> clearSearchHistory(@RequestAttribute("userId") Long userId) {
        return ApiResponse.success(searchService.clearUserSearchHistory(userId));
    }

    @GetMapping("/post")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    @ApiOperation("搜索帖子")
    public ApiResponse<Page<CommunityPostDetailDTO>> searchPosts(
            @ApiParam(value = "搜索关键词", required = true)
            @RequestParam String keyword,
            @ApiParam(value = "页码", defaultValue = "1")
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码不能小于1") Integer pageNum,
            @ApiParam(value = "每页条数", defaultValue = "10")
            @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页条数不能小于1") Integer pageSize) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            Page<CommunityPostDetailDTO> page = new Page<>(pageNum, pageSize);
            IPage<CommunityPostDetailDTO> result = searchService.searchPosts(currentUserId, keyword, page);
            
            // 记录搜索历史
            searchService.recordSearch(currentUserId, keyword, null);
            
            return ApiResponse.success(new Page<CommunityPostDetailDTO>(result.getCurrent(), result.getSize(), result.getTotal())
                .setRecords(result.getRecords()));
        } catch (Exception e) {
            log.error("搜索帖子失败: keyword={}, pageNum={}, pageSize={}, error={}", 
                keyword, pageNum, pageSize, e.getMessage(), e);
            return ApiResponse.error("搜索帖子失败");
        }
    }
} 